package com.niit.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;

@Component
public class HdfsTool {
    private Configuration conf;

    @Value("${hdfs.path}")
    private String hdfsPath;

    @Value("${hdfs.user}")
    private String hdfsUser;

    public HdfsTool() {
        conf = new Configuration();
    }
    public void putFileToHdfs(InputStream inputStream, String fileName,int gid) {
        new Thread(() -> {
            try {
                try (FileSystem fs = FileSystem.get(new URI(hdfsPath),conf,hdfsUser);
                     FSDataOutputStream fos = fs.create(new Path("/galgal/" + gid + "/" + fileName), true)) {
                    IOUtils.copyBytes(inputStream,fos,conf);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }



    public InputStream getFromHdfs(String fileName, int gid) throws Exception{
        FileSystem fs = FileSystem.get(new URI(hdfsPath),conf,hdfsUser);
        FSDataInputStream fis = fs.open(new Path("/galgal/" + gid + "/" + fileName));
        return fis;
    }





    public void deleteDir(int gid) throws Exception {
        FileSystem fs = FileSystem.get(new URI(hdfsPath),conf,hdfsUser);
        fs.delete(new Path("/galgal/" + gid ),true);
    }
}
